import React, { useEffect, useState } from 'react';
import '../index.css';

interface CostResult {
  newAverageCost: number;
}

const calculateNewCost = (currentPrice: number, currentShares: number, currentAverageCost: number, additionalShares: number) => {
  if (!currentPrice || !currentShares || !currentAverageCost || !additionalShares) {
    return null;
  }

  const totalCurrentInvestment = currentAverageCost * currentShares;
  const additionalInvestment = currentPrice * additionalShares;
  const newTotalShares = currentShares + additionalShares;
  const newTotalInvestment = totalCurrentInvestment + additionalInvestment;
  const newAverageCost = newTotalInvestment / newTotalShares;
  console.log(totalCurrentInvestment)
  console.log(additionalInvestment)
  console.log(newTotalInvestment)
  console.log(newAverageCost)

  return { newAverageCost };
};

const StockCostCalculator = () => {
  const [formData, setFormData] = useState({
    currentPrice: '',
    currentShares: '',
    currentAverageCost: '',
    additionalShares: ''
  });
  const [result, setResult] = useState<CostResult | null>(null);
  const [isSubmitted, setIsSubmitted] = useState(false);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  useEffect(() => {
    // 设置页面标题
    document.title = "股票成本计算器 - 轻松计算你的投资策略";
    let metaDescription = document.querySelector('meta[name="description"]') as HTMLMetaElement | null;
    // 创建或更新描述元标签
    if (!metaDescription) {
      metaDescription = document.createElement('meta');
      metaDescription.name = "description";
      document.head.appendChild(metaDescription);
    }
    metaDescription.content = "使用我们的股票成本计算器，轻松计算将来你的股票持有成本。";
    
    // 清理函数
    return () => {
      document.title = ""; // 重置标题
      if (metaDescription) {
        document.head.removeChild(metaDescription);
      }
    };
  }, []);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitted(true);
    const { currentPrice, currentShares, currentAverageCost, additionalShares } = formData;
    const calculationResult = calculateNewCost(
      parseFloat(currentPrice),
      parseInt(currentShares),
      parseFloat(currentAverageCost),
      parseInt(additionalShares)
    );
    setResult(calculationResult);
  };

  return (
    <div className="calculator-container">
      <h1 className="calculator-title">股票成本计算器</h1>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="currentAverageCost" className="form-label">当前持有股票均价：</label>
          <input
            type="number"
            id="currentAverageCost"
            name="currentAverageCost"
            value={formData.currentAverageCost}
            onChange={handleInputChange}
            step="0.01"
            required
            className="form-input"
          />
        </div>
        <div className="form-group">
          <label htmlFor="currentShares" className="form-label">当前持有股数：</label>
          <input
            type="number"
            id="currentShares"
            name="currentShares"
            value={formData.currentShares}
            onChange={handleInputChange}
            required
            className="form-input"
          />
        </div>
        
        <div className="form-group">
          <label htmlFor="currentPrice" className="form-label">股票现价：</label>
          <input
            type="number"
            id="currentPrice"
            name="currentPrice"
            value={formData.currentPrice}
            onChange={handleInputChange}
            step="0.01"
            required
            className="form-input"
          />
        </div>
        <div className="form-group">
          <label htmlFor="additionalShares" className="form-label">要购入股票数量：</label>
          <input
            type="number"
            id="additionalShares"
            name="additionalShares"
            value={formData.additionalShares}
            onChange={handleInputChange}
            required
            className="form-input"
          />
        </div>
        <button type="submit" className="submit-button">
          计算
        </button>
      </form>
      {isSubmitted && result && (
        <div className="result-container">
          <p>新的平均成本将是 <strong>{result.newAverageCost.toFixed(2)}</strong> 元。</p>
        </div>
      )}
      {isSubmitted && !result && (
        <div className="error-message">
          <p>请填写所有字段并点击计算按钮。</p>
        </div>
      )}
    </div>
  );
};

export default StockCostCalculator;
